import 'dart:io';

import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

import 'index.dart';

class VideoViewController extends SuperController {
  @override
  final VideoViewState state = VideoViewState();

  Future<void> initialization() async {
    String url = state.url;
    if (url.startsWith('http')) {
      state.player = VideoPlayerController.networkUrl(Uri.parse(url));
    } else if (url.startsWith('/asset')) {
      state.player = VideoPlayerController.asset(url);
    } else {
      state.player = VideoPlayerController.file(File(url));
    }
    state.player.addListener(() {
      update();
    });
    await state.player.initialize();
    state.chewieCtrl = ChewieController(
      optionsTranslation: OptionsTranslation(
          cancelButtonText: '取消', playbackSpeedButtonText: '倍速'),
      videoPlayerController: state.player,
      aspectRatio: state.player.value.aspectRatio,
      autoPlay: true,
      looping: true,
      materialProgressColors: ChewieProgressColors(
        playedColor: Colors.white,
        bufferedColor: Colors.white60,
        handleColor: Colors.white,
      ),
      cupertinoProgressColors: ChewieProgressColors(
        playedColor: Colors.white,
        bufferedColor: Colors.white60,
        handleColor: Colors.white,
      ),
      // useRootNavigator: false,
      allowedScreenSleep: false,
    );
    update();

    state.isShow.listen((p0) {
      if (p0) {
        state.player.play();
      } else {
        state.player.pause();
      }
    });
  }

  void playOrPause() {
    if (state.player.value.isPlaying) {
      state.player.play();
    } else {
      state.player.pause();
    }
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() async {
    super.onReady();
    // started();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
    state.player.dispose();
    state.chewieCtrl?.dispose();
  }

  @override
  void onDetached() {
    Get.log('-------onDetached');
  }

  @override
  void onInactive() {
    Get.log('-------onInactive');
  }

  @override
  void onPaused() {
    Get.log('-------onPaused');

    state.player.pause();
  }

  @override
  void onResumed() {
    Get.log('-------onResumed');
    state.player.play();
  }

  @override
  void onHidden() {
    state.player.pause();
  }
}
